package com.lam.framework.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.lam.common.utils.ServletUtils;
import com.lam.common.utils.StreamUtils;

/**
 * 可以多次获取requestBody数据的包装
 * @author lam
 */
public class RepeatableReadRequestWrapper extends HttpServletRequestWrapper {
	
	private final byte[] body; 

	public RepeatableReadRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		request.setCharacterEncoding(ServletUtils.CHARSET);
		body = StreamUtils.readStreamByte(request.getInputStream());
	}
	
	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}
	
	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(body);
		return new ServletInputStream() {
			@Override
			public int read() throws IOException {
				return bais.read();
			}

			public boolean isFinished() {
				return true;
			}

			public boolean isReady() {
				return true;
			}

			public void setReadListener(ReadListener readListener) {
			}
		};
	}

}